<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref, shallowRef, onBeforeUnmount } from "vue";
import {
  AddReportCommand,
  ReportPageResponse,
  UpdateReportCommand,
  addReportApi,
  updateReportApi
} from "@/api/airport/safetyManage/report.api";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
import {
  editorConfig,
  toolbarConfig,
  viewEditorConfig,
  encodeHtmlToBase64
} from "@/api/airport/inspection/inspection";
import "@wangeditor/editor/dist/css/style.css";

interface Props {
  type: "add" | "update";
  modelValue: boolean;
  row?: ReportPageResponse;
  deptTree: any[];
}



import {useUserStoreHook} from "@/store/modules/user";
import dayjs from "dayjs";
const userStore = useUserStoreHook(); // 获取用户状态管理实例
const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const formData = reactive({
  infoDescribe: undefined,
  infoSource: undefined,
  status: undefined,
  discoverer: undefined,
  contactPerson: undefined,
  dutyDeptId: undefined,
  acceptDeptId: undefined,
  basis: undefined,
  title: undefined,
  discoveryDate: undefined,
  discoveryPlace: undefined,
  feedback: undefined,
  createTime: undefined,
});

const rules: FormRules = {
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  discoveryDate: [{ required: true, message: "发现日期不能为空", trigger: "change" }],
  discoveryPlace: [{ required: true, message: "发现地点不能为空", trigger: "blur" }],
  dutyDeptId: [{ required: true, message: "责任单位不能为空", trigger: "change" }],
  acceptDeptId: [{ required: true, message: "处理部门不能为空", trigger: "change" }],
  basis: [{ required: true, message: "法律法规依据不能为空", trigger: "blur" }],
  infoDescribe: [{ required: true, message: "详细描述不能为空", trigger: "blur" }]
};
const formRef = ref<FormInstance>();

function handleOpened() {
  if (props.row) {
    Object.assign(formData, props.row);
  } else {
    formRef.value?.resetFields();
  }
}

const loading = ref(false);

async function handleConfirm() {
  formData.infoSource = '6';
  formData.status = '0';
  formData.discoverer = userStore.currentUserInfo?.userId;
  formData.contactPerson = userStore.currentUserInfo?.userId;

  formData.createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");



  await formRef.value.validate();

  try {
    loading.value = true;


    if (formData.infoDescribe) {
      formData.infoDescribe = encodeHtmlToBase64(formData.infoDescribe);
    }
    if (props.type === "add") {
      await addReportApi(formData);
    } else {
      await updateReportApi(formData);
    }
    ElMessage.success("提交成功");
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error(e);
    ElMessage.error((e as Error)?.message || "提交失败");
  } finally {
    loading.value = false;
  }
}

// 编辑器实例和配置
const editorRef = shallowRef();

onBeforeUnmount(() => {
  editorRef.value?.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="props.type === 'add' ? '手动上报' : '更新安全信息'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="form-container"
    >
      <el-form-item label="标题" prop="title" class="form-item">
        <el-input v-model="formData.title" size="default" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item label="发现日期" prop="discoveryDate" class="form-item">
        <el-date-picker v-model="formData.discoveryDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD HH:mm:ss"/>
      </el-form-item>

      <el-form-item label="发现地点" prop="discoveryPlace" class="form-item">
        <el-input v-model="formData.discoveryPlace" size="default" placeholder="请输入发现地点" />
      </el-form-item>


      <el-form-item label="责任单位" prop="deptId">
        <el-cascader
          v-model="formData.dutyDeptId"
          :options="deptTree"
          :props="{
        value: 'value',
        label: 'label',
        emitPath: false,
        checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="处理部门" prop="acceptDeptId">
        <el-cascader
          v-model="formData.acceptDeptId"
          :options="deptTree"
          :props="{
        value: 'value',
        label: 'label',
        emitPath: false,
        checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>


      <el-form-item label="法律法规依据" prop="basis" class="form-item">
        <el-input type="textarea" v-model="formData.basis" placeholder="请输入法律法规依据" />
      </el-form-item>


      <el-form-item label="详细描述" class="form-item" prop="infoDescribe">
        <div class="editor-wrapper">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 250px; overflow-y: hidden;"
            v-model="formData.infoDescribe"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>


      <el-form-item label="备注" class="form-item">
        <el-input type="textarea" v-model="formData.feedback" placeholder="请输入备注信息" />
      </el-form-item>


    </el-form>
  </v-dialog>
</template>

<style scoped>
.form-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}
.form-item {
  margin-bottom: 20px;
}
.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100%;
}
</style>
